#include "header/ProcessBase.h"
#include <iostream>

std::string theState(State s){
	static std::string states[3]={"RUN","RDY","FNS"};
	return states[s];
}

BaseProcesser::BaseProcesser(int p_n)
:to_exit(false),readyH(nullptr),readyT(nullptr),finish(nullptr),fini_num(0)
{
	p_num=0; 
	p_count = p_n;
	head = new PCB[p_n];
	head[p_n - 1].next = nullptr;
	head[p_n - 1].name = p_n - 1;
	head[0].pre=nullptr;
	for (size_t i = 0; i < p_count-1; i++)
	{
		head[i].name = i;
		head[i].next = head+i+1;
		head[i+1].pre=head+i;
	}
	empty=head;
}

BaseProcesser::~BaseProcesser()
{
	delete[]head;
}

void BaseProcesser::creat(int needtime)
{
	
	if (p_num >= p_count) 
	{
		std::cout<<"进程空间不足";
		return;
	}
	else if(!readyH && type!=MtF){	//第一个
		readyH=empty;
		readyT=empty;
		empty=empty->next;
		readyT->next=nullptr;
		readyH->cputime=0;
		readyH->needtime=needtime;
		readyH->prio=50-needtime;
		readyH->state=State::RDY;
		p_num++;
		return;
	}
	else{
		do_creat(needtime);
	}
}
void BaseProcesser::schadule()
{

    first_in();
	print();
	job();
}
void BaseProcesser::do_finish(){
	running->state=State::FNS;
	running->next=finish;
	if(finish)
		finish->pre=running;
	finish=running;
	running->pre=nullptr;
	fini_num++;
}
void BaseProcesser::print(){
	std::cout<<"\n\nname\tcputime\tprio\tneedtime\tstate\n";
	std::cout<<"now running:\n";
	PCB*p=running;
	if(p->state==RUN)
		std::cout<<p->name<<'\t'<<p->cputime<<'\t'<<p->prio<<'\t'<<p->needtime<<'\t'<<theState(p->state)<<std::endl<<std::endl;
	print_state();
}
void BaseProcesser::job(){
	if(do_job()){
		do_finish();
		if(fini_num==p_num)
			do_exit();
	}else{
		running->state=State::RDY;
		insert_back();
	}
}
void BaseProcesser::do_exit(){
	to_exit=true;
}
bool BaseProcesser::all_finish(){
	return to_exit;
}
void BaseProcesser::print_state(){
	PCB*p=readyH;
	std::cout<<"the readys:\n";
	while(p){
		std::cout<<p->name<<'\t'<<p->cputime<<'\t'<<p->prio<<'\t'<<p->needtime<<'\t'<<theState(p->state)<<std::endl;
		p=p->next;
	}
	std::cout<<"the finishs\n";
	p=finish;
	while(p){
		std::cout<<p->name<<'\t'<<p->cputime<<'\t'<<p->prio<<'\t'<<p->needtime<<'\t'<<theState(p->state)<<std::endl;
		p=p->next;
	}
}